<template>
    <div class="publish-container">
        <el-card class="box-card">
            <div slot="header">
                <!-- 导航 -->
                <el-breadcrumb separator-class="el-icon-arrow-right">
                    <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
                    <el-breadcrumb-item>编辑文章</el-breadcrumb-item>
                </el-breadcrumb>
                <!-- 导航 -->
            </div>
            <!-- 文章内容 -->
            <el-form ref="article-form"
                     :model="article"
                     :rules="valid"
                     label-width="150px">
                <el-form-item label="文章标题：" prop="title">
                    <el-input v-model="article.title"></el-input>
                </el-form-item>
                <el-form-item label="文章内容：" prop="content">
<!--                    <el-input type="textarea" :autosize="{ minRows: 5, maxRows: 7}" v-model="article.content"></el-input>-->
                    <el-tiptap
                        lang="zh"
                        v-model="article.content"
                        :extensions="extensions"
                        height="400"
                        placeholder="请输入文章内容"
                    ></el-tiptap>
                </el-form-item>
                <el-form-item label="频道：" prop="channel">
                    <el-select v-model="article.channel" placeholder="请选择文章发布频道">
                        <el-option v-for="item in channelList"
                                   :key="item.id"
                                   :label="item.type"
                                   :value="item.id"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="onSubmit">保存并发布</el-button>
                    <el-button type="info" @click="onBack">返回</el-button>
                </el-form-item>
            </el-form>
            <!-- 文章内容 -->
        </el-card>
    </div>
</template>

<script>
    // 局部导入富文本编辑器
    // import { ElementTiptap } from 'element-tiptap'
    // 初始化富文本编辑器功能部件
    import {
        // necessary extensions
        ElementTiptap,
        Doc,
        Text,
        Paragraph,
        Heading,
        Bold,
        Link,
        Underline,
        Italic,
        Strike,
        ListItem,
        BulletList,
        OrderedList,
        Image,
        CodeBlock,
        TextColor,
        TextHighlight,
        CodeView,
        TextAlign,
        Table,
        TableHeader,
        TableCell,
        TableRow,
        Blockquote,
        TodoItem,
        TodoList,
        Preview,
        Fullscreen
    } from 'element-tiptap'

    import 'element-tiptap/lib/index.css'
    import {adminUpload} from "../../../api/upload";
    import {getArticleChannelData} from "../../../api/article_channel";
    import {queryArticleById, updateArticle} from "../../../api/article";

    export default {
        name: "EditArticle",
        // 富文本编辑器组件
        components: {
            'el-tiptap': ElementTiptap
        },
        data() {
            return {
                article: {
                    id: '',
                    title: '',
                    content: '',
                    channel: '',
                    state: ''
                },
                channelList: [],
                extensions: [
                    new Doc(),
                    new Text(),
                    new Paragraph(),
                    new Heading({ level: 5 }),  //标题
                    new Bold({ bubble: true }), // 加粗
                    new Link(),         // 超链接
                    new Underline({ bubble: true, menubar: false }), // 下划线
                    new Blockquote(),   // 引用
                    new Italic(),       // 斜线
                    new Strike(),       // 删除线
                    new ListItem(),     // 列表
                    new BulletList(),   // 无需列表
                    new OrderedList(),  // 有序列表
                    new TextAlign(),    // 文本排版
                    new Table(),        // 表格
                    new TableHeader(),
                    new TableCell(),
                    new TableRow(),
                    new Image(
                        {         // 图片上传
                        // 自定义图片上传时间， 默认是生成base64和文本保存在一起（缺点：内存消耗太大）
                        uploadRequest(file) {
                            const imgData = new FormData()
                            imgData.append('file',file)
                            imgData.append('type','article')
                            return adminUpload(imgData).then(res => {
                                return res.data.data   // 上传图片url
                            })
                        }
                    }
                    ),
                    new CodeBlock(),    // 代码块
                    new CodeView(),     // 代码预览
                    new TextColor(),    // 文本颜色
                    new TextHighlight(),// 文本高亮
                    new TodoList(),     // 任务列表
                    new TodoItem(),
                    new Preview(),      // 预览
                    new Fullscreen()    // 编辑器全屏
                ],
                valid: {              // 表单控件验证
                    title: [
                        {required: true, message: '标题不能为空', trigger: 'blur'}
                    ],
                    content: [
                        {required: true, message: '内容不能为空', trigger: 'blur'}
                    ],
                    channel: [
                        {required: true, message: '频道不能为空', trigger: 'blur'}
                    ],

                }
            }
        },
        created() {
            this.article.id = this.$route.query.id
            this.loadArticleChannelData()   // 加载所有分类数据
            this.loadEditArticleData()      // 加载编辑文章数据
        },
        methods: {
            loadArticleChannelData() {
                getArticleChannelData().then(res => {
                    this.channelList = res.data.data
                })
            },
            loadEditArticleData() {
                queryArticleById({
                    'id': this.article.id
                }).then(res => {
                    const data = res.data.data
                    this.article.title = data.title
                    this.article.content = data.content
                    this.article.channel = data.channel
                })
            },
            onSubmit() {
                // 表单验证
                console.log(this.$refs['article-form'].validate((valid, error) => {
                    // 验证失败
                    if (!valid) {
                        return
                    }
                    // 验证通过 ，登录操作
                    this.onUpdateArticle()
                }))
            },
            onUpdateArticle() {
                updateArticle({
                    'id': this.article.id,
                    'title': this.article.title,
                    'channel': this.article.channel,
                    'content': this.article.content,
                }).then(res => {
                    if(res.data.code == 200){
                        this.$message({
                            message: "更新成功",
                            type: 'success'
                        })
                        this.$router.push('/queryArticleByCondition')
                    }else{
                        this.$message.error(res.data.msg)
                    }
                })
            },
            onBack() {
                this.$router.push('/queryArticleByCondition')
            }
        }

    }
</script>

<style scoped>

</style>
